package com.tange.ai.core.sample.play

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.view.*
import android.widget.FrameLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tange.ai.core.sample.R
import com.tange.ai.core.sample.utils.Utils
import com.tange.ai.core.sample.databinding.ActivityDevicePlaybackBinding
import com.tange.base.toolkit.*
import com.tange.base.ui.design.BasicMenuTextArrow
import com.tange.core.media.render.DeviceMediaRender
import com.tange.core.media.source.impl.cloud.CloudRecord
import com.tange.core.media.source.impl.cloud.CloudStorageMediaSource
import com.tange.core.media.source.impl.cloud.CloudStoragePlayback
import com.tange.module.media.play.util.BitmapUtil
import com.tg.appcommon.android.TGLog
import java.io.File

class CloudPlaybackActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "CloudPlaybackActivity_"
        private const val PARAM_DEVICE_ID = "PARAM_DEVICE_ID"

        fun launch(context: Context, deviceId: String) {
            context.startActivity(Intent(context, CloudPlaybackActivity::class.java).apply {
                putExtra(PARAM_DEVICE_ID, deviceId)
            })
        }
    }

    private var albumPath = Environment.getExternalStorageDirectory()
        .toString() + File.separator + Environment.DIRECTORY_DCIM

    private lateinit var deviceId: String

    private lateinit var binding: ActivityDevicePlaybackBinding

    private lateinit var deviceMediaRender: DeviceMediaRender

    private lateinit var cloudStorageMediaSource: CloudStorageMediaSource

    private var isLandscape = false
    private var rendered = false

    private lateinit var listAdapter: ListAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityDevicePlaybackBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
            Utils.setDarkStatusBar(this@CloudPlaybackActivity, Color.TRANSPARENT)
            listAdapter = ListAdapter()
            list.layoutManager = LinearLayoutManager(this@CloudPlaybackActivity, LinearLayoutManager.VERTICAL, false)
            list.adapter = listAdapter
            name.text = "云端录像"
        }

        deviceId = intent.getStringExtra(PARAM_DEVICE_ID)

        cloudStorageMediaSource = CloudStorageMediaSource(this, deviceId).apply {
            observeFirstFrameReceived {
                TGLog.i(TAG, "[first-received] ")
            }

            enableVideoProduce(true)
        }

        // 创建媒体播放器
        deviceMediaRender = DeviceMediaRender(this, cloudStorageMediaSource).apply {

            // 将播放器示例绑定到UI上
            attach(binding.playerContainer, createCenterLayoutParams())

            // 监听首帧数据渲染回调
            observeFirstFrameRendered {
                TGLog.i(TAG, "[first-rendered] ")
                rendered = true
                binding.loading.gone()
            }
        }

        binding.loading.visible()
        binding.audio.setImageDrawable(ContextCompat.getDrawable(this,
            R.drawable.ic_baseline_volume_off_24
        ))
        binding.audio.onClicked { switchAudio() }
        binding.screenShot.onClicked { screenshot() }
        binding.screenRecord.onClicked { screenRecord() }
        binding.fullScreen.onClicked { switchFullScreen() }
        binding.back.onClicked { finish() }
        binding.connect.onClicked {  }

        CloudStoragePlayback(deviceId).query(DateUtil.getTodayDate()) { resp ->

            if (resp.success) {
                if (resp.data?.size ?: 0 > 0) {
                    resp.data?.let {
                        listAdapter.refresh(it)
                        cloudStorageMediaSource.setDataSource(it[0].toDataSource())
                        cloudStorageMediaSource.seek(it[0].startTime ?: 0)
                    }
                } else {
                    binding.emptyView.visible()
                    binding.emptyView.text = "今日无云录像"
                }
            } else {
                if (resp.code == CloudStoragePlayback.ERROR_NO_RECORD) {
                    binding.emptyView.visible()
                    binding.emptyView.text = "今日无云录像"
                } else {
                    binding.emptyView.visible()
                    binding.emptyView.text = "获取云录像失败 ${resp.code}, ${resp.message}"
                }

                binding.loading.gone()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        TGLog.i(TAG, "[onResume] ")
        deviceMediaRender.enableVideoRender(true)
        cloudStorageMediaSource.enableVideoProduce(true)
    }

    override fun onPause() {
        super.onPause()
        TGLog.i(TAG, "[onPause] ")
        deviceMediaRender.enableAudioRender(false)
        cloudStorageMediaSource.enableVideoProduce(false)
        cloudStorageMediaSource.enableAudioProduce(false)
        binding.audio.setImageDrawable(ContextCompat.getDrawable(this,
            R.drawable.ic_baseline_volume_off_24
        ))
    }

    private fun createCenterLayoutParams() = FrameLayout.LayoutParams(
        FrameLayout.LayoutParams.MATCH_PARENT,
        FrameLayout.LayoutParams.MATCH_PARENT
    ).apply { gravity = Gravity.CENTER }

    private fun screenRecord() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                this.requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 100)
            }
            Tips.show("需要存储权限")
            return
        }

        if (deviceMediaRender.screenRecord().isStarted()) {
            val file = File(albumPath, "TG-${System.currentTimeMillis()}.mp4")
            deviceMediaRender.screenRecord().finish(file.absolutePath) {
                if (it) Tips.show("录屏已保存到 ${file.absolutePath}")
            }
            binding.screenRecord.setImageDrawable(ContextCompat.getDrawable(this,
                R.drawable.ic_baseline_videocam_24
            ))
        } else {
            deviceMediaRender.screenRecord().start()
            binding.screenRecord.setImageDrawable(ContextCompat.getDrawable(this,
                R.drawable.ic_baseline_videocam_off_24
            ))
            Tips.show("开始录屏，再次点击结束录屏")
        }
    }

    private fun switchAudio() {
        if (cloudStorageMediaSource.isAudioProduceEnabled()) {
            binding.audio.setImageDrawable(ContextCompat.getDrawable(this,
                R.drawable.ic_baseline_volume_off_24
            ))
            cloudStorageMediaSource.enableAudioProduce(false)
            deviceMediaRender.enableAudioRender(false)
        } else {
            binding.audio.setImageDrawable(ContextCompat.getDrawable(this,
                R.drawable.ic_baseline_volume_on_24
            ))
            cloudStorageMediaSource.enableAudioProduce(true)
            deviceMediaRender.enableAudioRender(true)
        }
    }

    private fun screenshot() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                this.requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 100)
            }
            Tips.show("需要存储权限")
            return
        }

        deviceMediaRender.screenshot()?.let {

            val file = File(albumPath, "TG-${System.currentTimeMillis()}.jpg")

            BitmapUtil.saveBitmapToFile(file, it, Bitmap.CompressFormat.JPEG)

            if (file.exists()) {
                val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
                val uri = Uri.fromFile(file)
                intent.data = uri
                sendBroadcast(intent)
                Tips.show("截图已保存到 ${file.absolutePath}")
            }
        }
    }

    private fun switchFullScreen() {
        if (isLandscape) {
            binding.bottomLayout.visibility = View.VISIBLE
            binding.topBar.visibility = View.VISIBLE
            binding.opButtons.visibility = View.VISIBLE
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
            isLandscape = false
        } else {
            binding.bottomLayout.visibility = View.GONE
            binding.topBar.visibility = View.GONE
            binding.opButtons.visibility = View.GONE
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
            isLandscape = true
            binding.playerContainer.postDelayed({
                Tips.show("使用物理返回键退出全屏")
            }, 1000)
        }

        binding.playerContainer.post {
            deviceMediaRender.resize()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean =
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            if (isLandscape) {
                switchFullScreen()
                true
            }
            else {
                finish()
                true
            }
        } else super.onKeyDown(keyCode, event)


    inner class ListAdapter : RecyclerView.Adapter<ViewHolder>() {
        private val apList: MutableList<CloudRecord> = java.util.ArrayList()
        fun refresh(list: List<CloudRecord>) {
            apList.clear()
            apList.addAll(list)
            notifyDataSetChanged()
        }

        override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
            val view: View = LayoutInflater.from(viewGroup.context)
                .inflate(R.layout.item_device_list, viewGroup, false)
            return ViewHolder(BasicMenuTextArrow(viewGroup.context))
        }

        override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
            val item = apList[position]
            viewHolder.menu.setBackgroundResource(R.drawable.basic_background_filled_round_neutral_10)
            viewHolder.menu.name.text = "${DateUtil.getStrToTime(item.startTime ?: 0)}"
            viewHolder.menu.desc.text = "至 ${DateUtil.getStrToTime(item.endTime ?: 0)}"
            viewHolder.menu.desc.visible()

            var lp: ViewGroup.LayoutParams? = viewHolder.menu.layoutParams
            if (lp == null) lp = RecyclerView.LayoutParams(RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT)
            lp.let {
                if (it is RecyclerView.LayoutParams) {
                    it.bottomMargin = 50
                    viewHolder.menu.layoutParams = it
                }
            }

            viewHolder.itemView.setOnClickListener { view: View? ->
                Toast.makeText(this@CloudPlaybackActivity, "切换到：${DateUtil.getStrToTime(item.startTime ?: 0)}，请稍候...", Toast.LENGTH_LONG).show()
                cloudStorageMediaSource.setDataSource(item.toDataSource())
                cloudStorageMediaSource.seek(item.startTime ?: 0)
                deviceMediaRender.reset()
            }
        }

        override fun getItemCount(): Int {
            return apList.size
        }
    }

    class ViewHolder(view: BasicMenuTextArrow) : RecyclerView.ViewHolder(view) {
        val menu: BasicMenuTextArrow

        init {
            menu = view
        }
    }
}